package com.peng.herostory;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameMsgEncoder extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (!(msg instanceof GeneratedMessageV3)) {
            super.write(ctx, msg, promise);
            return;
        }
        Integer msgCode = GameMsgRecognizer.getCodeByMsgClazz(msg.getClass());

        if (msgCode == null) {
            log.error("无法识别的消息类型：{}", msg);
            return;
        }


        byte[] msgBody = ((GeneratedMessageV3) msg).toByteArray();
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeShort((short) 0); // 写出消息长度, 目前写出 0 只是为了占位
        buffer.writeShort(msgCode); // 写出消息编号
        buffer.writeBytes(msgBody);
        WebSocketFrame webSocketFrame = new BinaryWebSocketFrame(buffer);
        super.write(ctx, webSocketFrame, promise);
    }
}
